package com.iqismart.shorturl.schedule;

import com.iqismart.shorturl.cache.UrlCountCache;
import com.iqismart.shorturl.websocket.MyWebSocket;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Auther sty
 * @createTime 2019-10-24 10:22
 */
@Component
public class CountSchedule {

    @Scheduled(cron="0 0 0 * * ?")
    public void run(){
        UrlCountCache.todayGet.set(0);
        UrlCountCache.todayAdd.set(0);
    }

    @Scheduled(initialDelay = 10000,fixedDelay = 1000)
    public void push(){
        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","count");
        jsonObject.put("todayGet",UrlCountCache.todayGet);
        jsonObject.put("todayAdd",UrlCountCache.todayAdd);
        jsonObject.put("totalAdd",UrlCountCache.totalAdd);
        jsonObject.put("totalGet",UrlCountCache.totalGet);
        jsonObject.put("d",UrlCountCache.map.get("d"));
        jsonObject.put("newUid",UrlCountCache.map.get("newUid"));
        jsonObject.put("newUsername",UrlCountCache.map.get("newUsername"));

        List<JSONObject> onlineUserList = new ArrayList<>();
        MyWebSocket.webSocketSet.forEach(w->{
            final JSONObject u = new JSONObject();
            u.put("uid",w.getUserId());
            u.put("username",w.getUserName());
            onlineUserList.add(u);
        });
        jsonObject.put("onlineUserCount",UrlCountCache.map.get("randomOnlineUserCount"));

        //jsonObject.put("onlineUserList", JSONArray.toJSONString(onlineUserList));
        MyWebSocket.sendMessageToAll(jsonObject.toJSONString());
    }

    @Scheduled(initialDelay = 10000,fixedDelay = 10000)
    public void randomOnlineUser(){
        int count = 0;
        try {
            count = Integer.parseInt(UrlCountCache.map.get("randomOnlineUserCount"));
        } catch (NumberFormatException e) {
            count = 1;
        }
        count += count(count);
        UrlCountCache.map.put("randomOnlineUserCount", count+"");
    }


    public boolean add(int old){
        int random =Double.valueOf(Math.random()*1000 + 1).intValue();
        final double i = 500+500 * Double.valueOf(old)/Double.valueOf(20);
        if(random < (i*1000D)){
            return false;
        }
        return true;
    }

    public int count(int old){
        int count = 1;
        int random =Double.valueOf(Math.random()*1000 + 1).intValue();
        if(100 < random && random < 700 ){
            count =  1;
        }

        if(700 < random && random < 900 ){
            count =  2;
        }

        if(900 < random && random < 1000 ){
            count =  3;
        }

        if(!add(old) && old > 20){
           count = -count;
        }

        return count;
    }
}
